package com.smartapp.update;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

//import com.vondear.rxtools.RxAppTool;
//import com.vondear.rxtools.RxFileTool;

public class MainActivity extends Activity {

	static {
		System.loadLibrary("SmartAppUpdate");
	}

	// 合成成功
	private static final int SUCCESS = 1;
	// 合成的APK签名和已安装的签名不一致
	private static final int FAIL_SING = -1;
	// 合成失败
	private static final int FAIL_ERROR = -2;
	// 获取源文件失败
	private static final int FAIL_GET_SOURCE = -3;
	public static final String PATH = Environment.getExternalStorageDirectory() + File.separator;

	public static final String PATH2 = "/data/data/com.smartapp.update/";
//	public static final String PATH = "/data/data/com.fengmang.myapplication/";
	public static final String NEW_APK_PATH = PATH + "SmartAppUpdate.apk";
//	public static final String NEW_APK_PATH = PATH + "bsdiff_old.apk";
	public static final String PATCH_PATH = PATH + "SmartAppUpdate.patch";
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();


	}

	void init(){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkPermission = this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
				return;
			}
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
			// 适配android11读写权限
			if (Environment.isExternalStorageManager()) {
				//已获取android读写权限
			} else {
				Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivityForResult(intent, 1);
				return;
			}

		}

		beforeUpdate();
//		 afterUpdate();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
			case 0:
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					init();
				} else {
//					CustomDialog.Builder customBuilder = new CustomDialog.Builder(this);
//					customBuilder.setTitle("温馨提示").setMessage("您需要在设置里打开存储空间权限！")
//							.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//								public void onClick(DialogInterface dialog, int which) {
//									dialog.cancel();
//									finishMine();
//								}
//							}).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.cancel();
//							Intent localIntent = new Intent();
//							localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//							localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//							localIntent.setData(Uri.fromParts("package", getPackageName(), null));
//							startActivity(localIntent);
//							finishMine();
//						}
//					});
//					customBuilder.create().show();
				}
				return;

			case 1:
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					init();
				} else {
				}
				return;

			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}

	/**
	 * 升级前的界面
	 */
	private void beforeUpdate() {
		setContentView(R.layout.activity_main);
		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("doing..");
		progressDialog.setCancelable(false);
		progressDialog.setCanceledOnTouchOutside(false);
		findViewById(R.id.update).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new UpdateApkTask().execute();

//				Intent i = new Intent(Intent.ACTION_VIEW);
//				if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
//					i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//					Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", new File(NEW_APK_PATH));
//					i.setDataAndType(contentUri, "application/vnd.android.package-archive");
//				}else {
//					i.setDataAndType(Uri.parse("file://" + NEW_APK_PATH), "application/vnd.android.package-archive");
//				}
//				startActivity(i);
			}
		});


//		copy(new File(PATH + "SmartAppUpdate.patch"), PATH2 + "SmartAppUpdate.patch");
//		copy(new File(PATH + "SmartAppUpdate.apk"), PATH2 + "SmartAppUpdate.apk");

		Log.e("beforeUpdate===", "===");
	}

	public void copy(File oldPath, String newPath) {
		try {
			FileInputStream fileInputStream = new FileInputStream(oldPath);
			FileOutputStream fileOutputStream = new FileOutputStream(newPath);
			byte[] buffer = new byte[1024];
			int byteRead;
			while ((byteRead = fileInputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, byteRead);
			}

			Log.e("copy===", fileInputStream+"==="+fileOutputStream);

			fileInputStream.close();
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (Exception e) {
			Log.e("copy===e", "==="+e);
			e.printStackTrace();
		}
	}

	/**
	 * 复制文件夹及其中的文件
	 *
	 * @param oldPath String 源文件夹路径
	 * @param newPath String 目的文件夹路径
	 */
	public boolean copyFolder(String oldPath, String newPath) {
		try {
			File newFile = new File(newPath);
			if (!newFile.exists()) {
				if (!newFile.mkdirs()) {
					return false;
				}
			}
			File oldFile = new File(oldPath);
			String[] files = oldFile.list();
			File temp;
			for (String file : files) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file);
				} else {
					temp = new File(oldPath + File.separator + file);
				}
				if (temp.isDirectory()) {
					copyFolder(oldPath + File.separator + file, newPath + File.separator + file);
				} else if (!temp.exists()) {
					return false;
				} else if (!temp.isFile()) {
					return false;
				} else if (!temp.canRead()) {
					return false;
				} else {
					FileInputStream fileInputStream = new FileInputStream(temp);
					FileOutputStream fileOutputStream = new FileOutputStream(newPath + File.separator + temp.getName());
					byte[] buffer = new byte[1024];
					int byteRead;
					while ((byteRead = fileInputStream.read(buffer)) != -1) {
						fileOutputStream.write(buffer, 0, byteRead);
					}
					fileInputStream.close();
					fileOutputStream.flush();
					fileOutputStream.close();
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 升级后的界面
	 */
	private void afterUpdate() {
		setContentView(R.layout.activity_main_new);
	}

	private class UpdateApkTask extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(String... params) {
			String oldApkSource = Utils.getSourceApkPath(MainActivity.this, getPackageName());

			Log.e("doInBackground===", "==="+oldApkSource);

			File file = new File(PATH2,"SmartAppUpdate.patch");
			File newFile = new File(PATH2,"SmartAppUpdate.apk");

			Log.e("doInBackground===1", file+"==="+file.exists()+"==="+newFile.exists());

//			return SUCCESS;
//			Utils.installApk(MainActivity.this, NEW_APK_PATH);

			if (!TextUtils.isEmpty(oldApkSource)) {
				int patchResult = -1;
				try {
					patchResult = BatchUtils.applyPatchToOwn(MainActivity.this, NEW_APK_PATH, PATCH_PATH);

					Log.e("doInBackground===2", file+"==="+file.exists()+"==="+newFile.exists());
				} catch (IOException e) {

					e.printStackTrace();
				}
				if (patchResult == 0) {
//					String signatureNew = Utils.getUnInstalledApkSignature(NEW_APK_PATH);
//					String signatureSource = Utils.getInstalledApkSignature(MainActivity.this, getPackageName());
//					if (!TextUtils.isEmpty(signatureNew) && !TextUtils.isEmpty(signatureSource) && signatureNew.equals(signatureSource)) {
//						return SUCCESS;
//					} else {
//						return FAIL_SING;
//					}

					return SUCCESS;
				} else {
					return FAIL_ERROR;
				}
			} else {
				return FAIL_GET_SOURCE;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			switch (result) {
			case SUCCESS:
				showShortToast("新apk已合成成功：" + NEW_APK_PATH);
//				Utils.installApk(MainActivity.this, PATH + "SmartAppUpdate.apk");

//				Utils.installApk(MainActivity.this, NEW_APK_PATH);		//Y

//				RxAppTool.installApp(MainActivity.this, PATH + "SmartAppUpdate.apk");
//				RxAppTool.installApp(MainActivity.this, NEW_APK_PATH);



				break;
			case FAIL_SING:
				showShortToast("新apk已合成失败，签名不一致");
				break;
			case FAIL_ERROR:
				showShortToast("新apk已合成失败");
				break;
			case FAIL_GET_SOURCE:
				showShortToast("无法获取packageName为" + getPackageName()
						+ "的源apk文件，只能整包更新了！");
				break;
			}
		}
	}
	
	private void showShortToast(final String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
}
